package router

import (
	"image/png"
	"net/http"
	"os"
	"time"

	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	"github.com/tungyao/cedar"
)

func CreateQrPng(str, name string) {
	qrCode, _ := qr.Encode(str, qr.M, qr.Auto)

	// Scale the barcode to 200x200 pixels
	qrCode, _ = barcode.Scale(qrCode, 200, 200)

	// create the output file
	file, _ := os.Create("./static/qr/" + name + ".png")
	defer file.Close()

	// encode the barcode as png
	png.Encode(file, qrCode)
}

var loginConnect = make(chan *Login, 100)

func AuthUrl(w http.ResponseWriter, r *http.Request, co *cedar.Core) {
	if user, pass, ok := r.BasicAuth(); ok {
		if ch := P.Get([]byte(r.URL.Query().Get("code"))).(chan *Login); ch != nil {
			if login := authUser(user, pass); login != nil {
				ch <- login
				http.Redirect(w, r, "/", 304)
			} else {
				ch <- nil
			}
		} else {
			http.Error(w, "RESET: need authorized!", http.StatusUnauthorized)
			return
		}
	} else {
		if !ok {
			w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
	}
}
func AuthConnect(w http.ResponseWriter, r *http.Request, co *cedar.Core) {
	select {
	case ss := <-P.Get([]byte(r.URL.Query().Get("code"))).(chan *Login):
		if ss != nil {
			nt := NewToken([]byte(ss.Name))
			co.Session.Set("login", nt)
			SetSession(nt, JsonEncode(ss))
			w.WriteHeader(200)
		} else {
			w.WriteHeader(503)
		}

	case <-time.After(60 * time.Second):
		w.Write([]byte("no"))
	}
}
